// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js

var app = angular.module('myapp', ['ionic',
    'ngCordova',
    'ionic-citypicker',
    'ngCordovaBluetoothLE',
    'ngAnimate',
    'ionic.native',
    'myapp.BthSevice',
    'myapp.FetchDataService',
    'myapp.SPAService',
    'myapp.AddressSevice',
    'myapp.PopupService',
    'radialIndicator',
    'ionic-datepicker'
]);
/*$cordovaToast,*/
app.run(function ($ionicPlatform, $cordovaVibration, $cordovaToast, AddressSevice, $ionicPopup, $mydialog, $rootScope, $cordovaDeeplinks, $ionicHistory, $location, $timeout, $interval, $state, $ionicLoading, BthSevice, $http, $myconfig, SPAService, FetchDataService) {
    // var go_url = "http://localhost:8100/#/app/login";
    $ionicPlatform.ready(function () {
        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            cordova.plugins.Keyboard.disableScroll(true);
        }
        if (window.StatusBar) {
            StatusBar.styleDefault();
        }
        // 更新用户地理位置
        if (localStorage.getItem('user')) {
            function fn(val) {
                // console.log(val);
                $http.post($myconfig.api.base_host + '/users/update_point', {
                    "point": val
                }).then(function (res) {
                    console.log(res);
                });
            }

            AddressSevice.getPosition(fn);
        }

        FetchDataService.initData();

        $rootScope.isKeepConnect = false;
        if (localStorage.getItem('addr')) {
            BthSevice.initialize();
        }

        //先清理所有通知
        if (device.platform == "Android") {
            cordova.plugins.notification.local.cancel(1000, function () {
                console.log('本地通知已取消');
            });
            cordova.plugins.notification.local.cancel(1001, function () {
                console.log('本地通知已取消');
            });
        }else {
            window.plugins.jPushPlugin.clearAllLocalNotifications();
        }


        // //初始化通知列表数据id数组
        var noticId = [];
        var noticeListData;
        var newsDetail = function (notId) {
            if (noticId.length == 1) {
                noticId.splice(0, 1, Number(notId));
            } else if (!noticId.length) {
                noticId.push(Number(notId));
            }
            // $scope.noticeList = function(){
            // console.log($myconfig.api.base_host + '/notice/notice_list?notice_id=' + $scope.noticId);
            $http.post($myconfig.api.base_host + '/notice/notice_list', {
                ids: noticId
            }).then(function (res) {
                if (localStorage.getItem('noticeLIST')) {
                    var obj = JSON.parse(localStorage.getItem('noticeLIST'))
                    for (var i = 0; i < res.data.data.length; i++) {
                        obj.push(res.data.data[i]);
                    }
                    localStorage.setItem('noticeLIST', JSON.stringify(obj));
                } else {
                    localStorage.setItem('noticeLIST', JSON.stringify(res.data.data));
                }
            });
            $state.go('app.notice_data', {id: notId});
        };


        var jPush = {
            initJPush: function () {
                window.plugins.jPushPlugin.init();
                //调试模式，这样报错会在应用中弹出一个遮罩层显示错误信息
                window.plugins.jPushPlugin.setDebugMode(true);
                var onGetRegistradionID = function (data) {
                    console.log(data);
                };

                if (device.platform != "Android") {
                    window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
                }

                window.plugins.jPushPlugin.getUserNotificationSettings(function (result) {
                    if (result == 0) {
                        // 系统设置中已关闭应用推送。
                    } else if (result > 0) {
                        // 系统设置中打开了应用推送。
                    }
                });

                //应用前台时收到通知触发
                document.addEventListener("jpush.receiveNotification", function (event) {

                    var alertContent;
                    if (device.platform == "Android") {
                        alertContent = event.alert;
                    } else {
                      //先看看是不是本地通知
                      if(event.__JPUSHNotificationKey && (event.__JPUSHNotificationKey == '1000' || event.__JPUSHNotificationKey == '1001' || event.__JPUSHNotificationKey == '1')){
                        handleNotificationTrigger(Number(event.__JPUSHNotificationKey)); //处理通知触发
                        return;
                      }
                        // alertContent = event.aps.alert;

                    }
                    // alert("open Notificaiton:" + alertContent);
                }, false);

                //应用后台时收到通知触发
                document.addEventListener("jpush.backgroundNotification", function (event) {

                    var alertContent;
                    if (device.platform == "Android") {
                        alertContent = event.alert;
                    } else {
                      //先看看是不是本地通知
                      if(event.__JPUSHNotificationKey && (event.__JPUSHNotificationKey == '1000' || event.__JPUSHNotificationKey == '1001' || event.__JPUSHNotificationKey == '1')){
                        handleNotificationTrigger(Number(event.__JPUSHNotificationKey)); //处理通知触发
                        return;
                      }

                    }
                    // alert("open Notificaiton:" + alertContent);
                }, false);

                //自定义消息推送
                document.addEventListener("jpush.receiveMessage", function (event) {
                    var message
                    if(device.platform == "Android") {
                        message = event.message;
                    } else {
                        message = event.content;
                    }
                }, false);

                window.plugins.jPushPlugin.getRegistrationID(onGetRegistradionID);
                //document.addEventListener("jpush.receiveNotification", this.onJPushReceiveNotification, false);
                document.addEventListener("jpush.openNotification", this.onOpenNotification, false);

            },
//应用内接收通知触发
            /*onJPushReceiveNotification: function () {
             var content;
             if (device.platform == "Android") {
             content = window.plugins.jPushPlugin.receiveNotification;
             } else {
             content = event.aps.alert;
             }
             //alert("open Notificaiton:"+alertContent);
             //alert("open Notificaiton:"+JSON.stringify(window.plugins.jPushPlugin.receiveNotification));
             newsDetail(content.extras['cn.jpush.android.EXTRA'].newsid);
             window.plugins.jPushPlugin.clearAllNotification();//清除通知
             },*/
//点击手机通知列表后进入应用触发
            onOpenNotification: function (event) {
//   var content;
                var newsid, type;
                if (device.platform == "Android") {
                    // content = window.plugins.jPushPlugin.openNotification;
                    // newsid = content.extras['cn.jpush.android.EXTRA'].newsid;
                    newsid = event.extras.id;
                    type = event.extras.type;
                    // newsDetail(newsid); //去看通知详情
                    // return;
                } else {
                  window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
                  if(event.__JPUSHNotificationKey && (event.__JPUSHNotificationKey == '1000' || event.__JPUSHNotificationKey == '1001' || event.__JPUSHNotificationKey == '1')){
                    handleNotificationClick(Number(event.__JPUSHNotificationKey)); //处理通知触发
                    return;
                  }
                  newsid = event.id;
                  type = event.type;
                }
                if(type && type == 'red'){
                    // detailRed();
                    $state.go('app.red', { //newsid这里是红包id
                        id: newsid
                    });
                }else{
                    newsDetail(newsid);
                }

            },
            isOpenPush: function () {
                window.plugins.jPushPlugin.getUserNotificationSettings(function (result) {
                    if (result == 0) {
                        console.log('系统设置中已关闭应用推送。');
                    } else if (result > 0) {
                        console.log('系统设置中打开了应用推送。');
                    }
                })
            }
        }

        setTimeout(function () {
            //极光推送
            jPush.initJPush();
        }, 1500);

        setTimeout(function () {
            //极光推送
            jPush.isOpenPush();
        }, 2500);


        // //初始化通知列表数据id数组
        // var noticId = [];
        // var noticeListData;
        // //推送初始化
        // var setTagsWithAliasCallback = function(event) {
        //     window.alert('result code:' + event.resultCode + ' tags:' + event.tags + ' alias:' + event.alias);
        // }
        // var openNotificationInAndroidCallback = function(data) {
        //     var json = data;
        //     // window.alert(json);
        //     if (typeof data === 'string') {
        //         json = JSON.parse(data);
        //     }
        //     var id = json.extras['cn.jpush.android.EXTRA'].id;
        //     //window.alert(id);
        //     var alert = json.extras['cn.jpush.android.ALERT'];
        //     if (noticId.length == 1) {
        //         noticId.splice(0, 1, Number(id));
        //     } else if (!noticId.length) {
        //         noticId.push(Number(id));
        //     }
        // var newsDetail = function(noticId){

        //     // $scope.noticeList = function(){
        //     // console.log($myconfig.api.base_host + '/notice/notice_list?notice_id=' + $scope.noticId);
        //     $http.post($myconfig.api.base_host + '/notice/notice_list', {
        //         ids: noticId
        //     }).then(function(res) {
        //         if (localStorage.getItem('noticeLIST')) {
        //             var obj = JSON.parse(localStorage.getItem('noticeLIST'))
        //             for (var i = 0; i < res.data.data.length; i++) {
        //                 obj.push(res.data.data[i]);
        //             }
        //             localStorage.setItem('noticeLIST', JSON.stringify(obj));
        //         } else {
        //             localStorage.setItem('noticeLIST', JSON.stringify(res.data.data));
        //         }
        //     });
        //     $state.go('app.notice_data', { id: id });
        // };
        // }
        // var config = {
        //     stac: setTagsWithAliasCallback,
        //     oniac: openNotificationInAndroidCallback
        // };

        // jpushService.init(config);

        // //启动极光推送服务
        // window.plugins.jPushPlugin.init();
        // window.plugins.jPushPlugin.setDebugMode(true);

        BthSevice.enable(); // 开启蓝牙
        // BthSevice.initialize(); // 开始连接设备
        $rootScope.$on('BthConnect', function (event, data) { // 监听未连接成功的广播事件
            if (data == "failed") {
                var myPopup = $ionicPopup.show({
                    templateUrl: 'templates/bitongbao/module/lanya.html',
                    scope: $rootScope
                });
                $rootScope.myclose = function () {
                    $ionicPopup.close();
                    $ionicHistory.nextViewOptions({
                        disableAnimate: true,
                        disableBack: true,
                        historyRoot: true
                    });
                    $state.go('app.MyLink');
                };
            }
        });

        // alert($cordovaDeeplinks);

        $cordovaDeeplinks.route({
            '/app/login': {
                target: 'app.login',
                parent: '/'
            }
        }).subscribe(function (match) {
            // One of our routes matched, we will quickly navigate to our parent
            // view to give the user a natural back button flow
            $timeout(function () {
                // $state.go(match.$route.parent, match.$args);
                $timeout(function () {
                    $state.go(match.$route.target);
                }, 20);
            }, 10); // Timeouts can be tweaked to customize the feel of the deeplink
        }, function (nomatch) {
            // console.warn('No match', nomatch);
        });

        //检测客户端是否安装有微信
        Wechat.isInstalled(function (installed) {
            console.log("Wechat installed: " + (installed ? "Yes" : "No"));
        }, function (reason) {
            console.log("Failed: " + reason);
        });


        //检测是否有安装qq客户端
        QQSDK.checkClientInstalled(function () {
            console.log('client is installed');
        }, function () {
            // if installed QQ Client version is not supported sso,also will get this error
            console.log('client is not installed');
        });


    });

    //判定当前设备类型是ios还是android
    var u = navigator.userAgent;
    // var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if (isiOS) {
        $rootScope.Is_Ios = true;
    }
    window.onerror = function (msg, url, line) {
        var idx = url.lastIndexOf("/");
        if (idx > -1) {
            url = url.substring(idx + 1);
        }
        // alert("ERROR in " + url + " (line #" + line + "): " + msg);
        return false;
    };


    $ionicPlatform.on('pause', function () {
        // $rootScope.$broadcast('stopInterval', true);

        if(SPAService.upKeepData.type){
            SPAService.upKeepData.backtime = new Date().getTime(); //记录返回到首页的时间
            SPAService.upKeepData.backts = SPAService.upKeepData.ts; //保存一份后台的倒计时时间
            SPAService.upKeepData.backrotateCount = SPAService.upKeepData.rotateCount; //保存一份后台时间旋转的角度
            SPAService.upKeepData.backprogress = SPAService.upKeepData.progress; //保存一份后台的倒计时进度
            SPAService.upKeepData.maintain_sta = 1; //从这里返回默认为可以保养完成
            console.log('程序后台运行时间：' + SPAService.upKeepData.backtime);
        }else if(SPAService.coryzaData.type){
            SPAService.coryzaData.backtime = new Date().getTime(); //记录返回到首页的时间
            SPAService.coryzaData.backts = SPAService.coryzaData.ts; //保存一份后台的倒计时时间
            SPAService.coryzaData.backrotateCount = SPAService.coryzaData.rotateCount; //保存一份后台时间旋转的角度
            SPAService.coryzaData.backprogress = SPAService.coryzaData.progress; //保存一份后台的倒计时进度
            SPAService.coryzaData.maintain_sta = 1; //从这里返回默认为可以保养完成
        }
        console.log('程序退出到后台了。');
        if ($rootScope.start == true) {
            // $rootScope.isPause = true; //保养中的时候变成true 如果用户短时间内
            //消息提醒
            // $timeout(function () {
            //     if($rootScope.isPause){
            if (device.platform == 'Android') {
              cordova.plugins.notification.local.schedule({
                  id: 1,
                  title: '健康保养',
                  text: '您正在进行' + $rootScope.mode + '保养，保养完成后会自动停止。',
                  at: new Date().getTime() + 5000, //5秒后触发，用户短时间内resume恢复app直接取消通知
                  // badge: 1,
                  autoClear: true, //默认值
                  sound: 'res://platform_default', //默认值
                  icon: 'res://drawable-xxxhdpi/icon.png', //默认值
                  ongoing: false //默认值
              });
            }else{
              window.plugins.jPushPlugin.addLocalNotificationForIOS(
                5, //5秒之后
                '您正在进行' + $rootScope.mode + '保养，保养完成后会自动停止。',
                1, //app图标设置角标
                "1", //通知标识符
                {"key":"value"}
              );
            }
                // }
            // }, 5000);
        }
    });

    $ionicPlatform.on('resume', function () {

      // cordova.plugins.notification.local.cancel(1, function () { //先取消，等继续后再创建定时器
      //     console.log('本地通知已取消');
      // });
      if (device.platform == "Android") {
        cordova.plugins.notification.local.cancel(1, function () {
            console.log('本地通知已取消');
        });
      }else { //ios直接清楚本地通知的所有对象，清除所有，应该没有其他的了吧
          window.plugins.jPushPlugin.clearAllLocalNotifications();
        window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
        window.plugins.jPushPlugin.deleteLocalNotificationWithIdentifierKeyInIOS("1"); //清除标识符为1的通知
      }
      //如果用户正在保养中并且在保养界面那就恢复倒计时的转动效果
      console.log('从后台恢复');
      if($rootScope.start && (SPAService.upKeepData.thePage || SPAService.coryzaData.thePage)){
          $rootScope.$broadcast('isResume', true); //广播从后台恢复的事件
          setTimeout(function () {
              $rootScope.$broadcast('isResume', false); //广播从后台恢复的事件
          }, 1000);
      }
    });

    setTimeout(function () {
        //本地通知调用时触发
        cordova.plugins.notification.local.on('schedule', function (notification) {
            // alert('触发定时器:' + notification.id);
        });

        //通知触发
        cordova.plugins.notification.local.on('trigger', function (notification) {
            // console.log(JSON.stringify(notification));
            handleNotificationTrigger(notification.id);
        });

        //监听点击事件
        cordova.plugins.notification.local.on('click', function (notification) {
            handleNotificationClick(notification.id);
        });
    }, 3000);

    function handleNotificationTrigger(notification_id){

      console.log('通知触发......');
      if(notification_id == 1000 && !SPAService.coryzaData.thePage){ //完成保养并且没有在保养页面
          console.log('更新鼻光宝保养记录......');
          SPAService.backgroundRunning(true, function () {

          }); //完成保养
      }else if(notification_id == 1001 && !SPAService.upKeepData.thePage){ //这是保养完成触发的定时器
          console.log('更新焕颜宝保养记录......');
          SPAService.backgroundRunningYZB(true, function () {

          }); //完成保养
      }
    }

    function handleNotificationClick(notification_id){
      console.log(notification_id);
      //点击的时候可跳转到对应的保养完成界面
      if(notification_id == 1000 && !SPAService.coryzaData.thePage){ //这是保养完成触发的定时器
          SPAService.goCoryzaEnd();
          if (device.platform == "Android") {
            cordova.plugins.notification.local.cancel(1000, function () {
                console.log('本地通知已取消');
            });
          }else {
            window.plugins.jPushPlugin.clearAllLocalNotifications();
          }
          // cordova.plugins.notification.local.cancel(1000, function () {
          //     // Notification was cancelled
          //     console.log('注销定时器')
          // });
      }else if(notification_id == 1001 && !SPAService.upKeepData.thePage){ //这是保养完成触发的定时器
          SPAService.goCoryzaEnd();
          // cordova.plugins.notification.local.cancel(1001, function () {
          //     // Notification was cancelled
          //     console.log('注销定时器')
          // });
          if (device.platform == "Android") {
            cordova.plugins.notification.local.cancel(1000, function () {
                console.log('本地通知已取消');
            });
          }else {
            window.plugins.jPushPlugin.clearAllLocalNotifications();
          }
      }
    }

    //双击退出
    $ionicPlatform.registerBackButtonAction(function (e) {
        //判断处于哪个页面时双击退出
        if ($location.path() == '/app/BiGuangBao' || $location.path() == '/app/YanZhiBao' || $location.path() == '/app/MyLink' || $location.path() == '/app/home' || $location.path() == '/app/message' || $location.path() == '/app/notice' || $location.path() == '/app/vip') {
            if ($rootScope.backButtonPressedOnceToExit) {
                BthSevice.isScanning(function (res) { // 先判断扫描状态，停止后再扫描
                    BthSevice.isConnect(function (status) { // 是否是连接状态，关闭后扫描
                        if (res.isScanning) {
                            console.log('关闭app停止扫描........');
                            BthSevice.stopScan();
                        }
                        if (status) {
                            console.log('关闭app先断开........');
                            BthSevice.closeLED(BthSevice.address);
                            $timeout(function () {
                                BthSevice.closeConn(BthSevice.address);
                            }, 300);
                        }
                        $timeout(function () { //600毫秒后关闭app
                            ionic.Platform.exitApp();
                        }, 800);
                    });
                });

            } else {
                $rootScope.backButtonPressedOnceToExit = true;
                $cordovaToast.showShortCenter('再按一次退出程序');
                setTimeout(function () {
                    $rootScope.backButtonPressedOnceToExit = false;
                }, 2000);
            }
        } else if ($ionicHistory.backView()) {
            $ionicHistory.goBack();
        } else {
            $rootScope.backButtonPressedOnceToExit = true;
            $cordovaToast.showShortCenter('再按一次退出程序');
            setTimeout(function () {
                $rootScope.backButtonPressedOnceToExit = false;
            }, 2000);
        }
        e.preventDefault();
        return false;
    }, 101);

    // $rootScope.tologin = function(){
    // var myPopup = $ionicPopup.show({
    //             templateUrl: 'templates/bitongbao/module/tologin.html',
    //             scope: $rootScope
    //         });
    //         $rootScope.myclose = function() {
    //             myPopup.close();
    //         };
    // $rootScope.err = '登陆过期，请重新登录';
    // $mydialog.fail($rootScope);
    // setTimeout(function(){
    //     localStorage.clear();
    //     $state.go('app.login');
    // },1000);
    $http.post($myconfig.api.base_host + '/users/update_token', {
        "refresh_token": localStorage.getItem('refresh_token')
    }).then(function (res) {
        // console.log(res.data);
        // return;
        if (res.data.success) {
            localStorage.setItem('token', res.data.info.access_token);
            localStorage.setItem('refresh_token', res.data.info.refresh_token);
            localStorage.setItem('user', JSON.stringify(res.data.info.user));
            $rootScope._RootUser = res.data.info.user;
            // $scope.success = true;
            // location.reload();
        } else {
            $rootScope.err = res.data.data;
            $mydialog.fail($rootScope);
        }
    });
    // };
})

    .config(['$stateProvider', '$urlRouterProvider', '$httpProvider', function ($stateProvider, $urlRouterProvider, $httpProvider) {

        $httpProvider.interceptors.push('TokenInterceptor');

        $stateProvider
            .state('app', {
                url: '/app',
                abstract: true,
                templateUrl: 'templates/menu.html',
                controller: 'MenuCtrl'
            })
            .state('app.canvas', {
                url: '/canvas',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/canvas/canvas.html'
                    }
                }
            })
            .state('app.FontStyle', { //字体
                url: '/FontStyle',
                templateUrl: 'templates/bitongbao/FontStyle.html',
            })
            .state('app.Background', { //背景颜色
                url: '/Background',
                templateUrl: 'templates/bitongbao/Background.html',
            })
            .state('app.Box', { //定义盒子
                url: '/Box',
                templateUrl: 'templates/bitongbao/Box.html',
            })
            .state('app.guidance', { //蓝牙连接提示
                url: '/guidance',
                views: {
                    'menuContent': {
                        controller: 'guidancePageCtrl',
                        templateUrl: 'templates/bitongbao/guidance.html',
                    }
                }
            })
            .state('app.MyLink', { //蓝牙连接
                url: '/MyLink',
                cache: false,
                views: {
                    'menuContent': {
                        templateUrl: 'templates/bitongbao/MyLink.html',
                        controller: 'LinkCtrl'
                    }
                }
            })
            .state('app.MyLinking', { //蓝牙设备页面
                url: '/MyLink/MyLinking',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/bitongbao/MyLinking.html',
                        controller: 'MyLinkingCtrl'
                    }
                }
            })
            .state('app.BiGuangBao', { //金鼻光主界面
                url: '/BiGuangBao',
                cache: false,
                views: {
                    'menuContent': {
                        templateUrl: 'templates/bitongbao/mode/BiGuangBao.html',
                        controller: 'BiGuangBaoCtrl'
                    }
                }
            })
            .state('app.YanZhiBao', { //焕颜宝主界面
                url: '/YanZhiBao',
                cache: false,
                views: {
                    'menuContent': {
                        templateUrl: 'templates/bitongbao/mode/YanZhiBao.html',
                        controller: 'YanZhiBaoCtrl'
                    }
                }
            })
            .state('app.UpKeeping', { //焕颜宝使用倒计时界面
                url: '/UpKeeping/:type',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'UpKeepingCtrl',
                        templateUrl: 'templates/bitongbao/mode/YZB/UpKeeping.html',
                    }
                }
            })
            .state('app.Coryza', { //金鼻光使用倒计时界面
                url: '/Coryza/:type',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'CoryzaCtrl',
                        templateUrl: 'templates/bitongbao/mode/BGB/Coryza.html',
                    }
                }
            })
            .state('app.CoryzaEnd', { //治疗完成
                url: '/Coryza/CoryzaEnd/:type',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'CoryzaEndCtrl',
                        templateUrl: 'templates/bitongbao/mode/BGB/CoryzaEnd.html',
                    }
                }
            })
            .state('app.UpKeepingEnd', { //治疗完成
                url: '/UpKeeping/UpKeepingEnd/:type',
                cache: false,
                views: {
                    'menuContent': {
                        controller: "UpKeepingEndCtrl",
                        templateUrl: 'templates/bitongbao/mode/YZB/UpKeepingEnd.html',
                    }
                }
            })
            .state('app.BGBInstructions', { //金鼻光使用说明
                url: '/BGBInstructions',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/bitongbao/mode/BGB/BGBInstructions.html',
                    }
                }
            })
            .state('app.YZBInstructions', { //焕颜宝使用说明
                url: '/YZBInstructions',
                cache: false,
                views: {
                    'menuContent': {
                        templateUrl: 'templates/bitongbao/mode/YZB/YZBInstructions.html',
                    }
                }
            })
            .state('app.login', { //用户登录界面
                url: '/login',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'loginPageCtrl',
                        templateUrl: 'templates/login/login.html',
                    }
                }
            })
            .state('app.logintowx', { //用户登录界面
                url: '/logintowx',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'loginPageCtrl',
                        templateUrl: 'templates/login/logintowx.html',
                    }
                }
            })
            .state('app.loginWX', { //用户微信登录界面
                url: '/loginWX',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'loginWXPageCtrl',
                        templateUrl: 'templates/login/loginWX.html',
                    }
                }
            })
            .state('app.findpwd', { //用户找回密码界面
                url: '/findpwd/:phoNum',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'findpwdPageCtrl',
                        templateUrl: 'templates/login/findpwd.html',
                    }
                }
            })
            .state('app.enterpwd', { //用户输入密码界面
                url: '/enterpwd/:mes',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'enterpwdPageCtrl',
                        templateUrl: 'templates/login/enterpwd.html',
                    }
                }
            })
            .state('app.perfectinfo', { //用户完善信息界面
                url: '/perfectinfo/:next',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'perfectinfoPageCtrl',
                        templateUrl: 'templates/login/perfectinfo.html',
                    }
                }
            })
            .state('app.register', { //用户注册界面
                url: '/register',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'registerPageCtrl',
                        templateUrl: 'templates/login/register.html',
                    }
                }
            })
            .state('app.home', { //首页-未登录
                url: '/home',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'homePageCtrl',
                        templateUrl: 'templates/homepage/home.html',
                    }
                }
            })
            .state('app.onlog', { //首页-已登录-未绑定设备
                url: '/onlog',
                cache: false,
                views: {
                    'menuContent': {
                        templateUrl: 'templates/homepage/onlog.html',
                    }
                }
            })
            .state('app.logd', { //首页-已登录-设备连接
                url: '/logd',
                cache: false,
                views: {
                    'menuContent': {
                        templateUrl: 'templates/homepage/logd.html',
                    }
                }
            })
            .state('app.setup_about_service', { //服务协议  隐私政策
                url: '/setup_about_service/:Mes',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'setupAboutServicePageCtrl',
                        templateUrl: 'templates/vip/setup_about_service.html',
                    }
                }
            })
            // .state('app.setup_about_yinsi', { //隐私政策
            //     url: '/setup_about_yinsi/:Mes',
            //     cache: false,
            //     views: {
            //         'menuContent': {
            //             controller: 'setupAboutYinsiPageCtrl',
            //             templateUrl: 'templates/vip/setup_about_yinsi.html',
            //         }
            //     }
            // })
            .state('app.setup_about', { //关于我们
                url: '/setup_about',
                views: {
                    'menuContent': {
                        controller: 'setupAboutPageCtrl',
                        templateUrl: 'templates/vip/setup_about.html',
                    }
                }
            })
            .state('app.setup_idea', { //意见反馈
                url: '/setup_idea',
                views: {
                    'menuContent': {
                        controller: 'setupIdeaPageCtrl',
                        templateUrl: 'templates/vip/setup_idea.html',
                    }
                }
            })
            .state('app.setup', { //设置
                url: '/setup',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'setupPageCtrl',
                        templateUrl: 'templates/vip/setup.html',
                    }
                }
            })
            .state('app.vip_device', { //我的设备管理
                url: '/vip_device',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipDevicePageCtrl',
                        templateUrl: 'templates/vip/vip_device.html',
                    }
                }
            })
            .state('app.vip_integral_rule', { //健康豆规则
                url: '/vip_integral_rule',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipIntegralRulePageCtrl',
                        templateUrl: 'templates/vip/vip_integral_rule.html',
                    }
                }
            })
            .state('app.vip_integral_task', { //健康豆任务
                url: '/vip_integral_task/:name',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipIntegralTaskPageCtrl',
                        templateUrl: 'templates/vip/vip_integral_task.html',
                    }
                }
            })
            .state('app.vip_integral', { //我的健康豆
                url: '/vip_integral',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipIntegralPageCtrl',
                        templateUrl: 'templates/vip/vip_integral.html',
                    }
                }
            })
            .state('app.vip_log', { //使用记录
                url: '/vip_log',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipLogPageCtrl',
                        templateUrl: 'templates/vip/vip_log.html',
                    }
                }
            })
            .state('app.vip_message_name', { //修改姓名
                url: '/vip_message_name/:name',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipMessageNamePageCtrl',
                        templateUrl: 'templates/vip/vip_message_name.html',
                    }
                }
            })
            .state('app.vip_message_newphone', { //新电话号码
                url: '/vip_message_newphone/:NewPon',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipMessageNewphonePageCtrl',
                        templateUrl: 'templates/vip/vip_message_newphone.html',
                    }
                }
            })
            .state('app.vip_message_newpwd', { //新密码
                url: '/vip_message_newpwd/:NewPwd',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipMessageNewpwdPageCtrl',
                        templateUrl: 'templates/vip/vip_message_newpwd.html',
                    }
                }
            })
            .state('app.vip_message_phone', { //修改电话号码
                url: '/vip_message_phone/:phoNo',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipMessagePhonePageCtrl',
                        templateUrl: 'templates/vip/vip_message_phone.html',
                    }
                }
            })
            .state('app.vip_message_pwdverify', { //修改密码
                url: '/vip_message_pwdverify/:phoNo',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipMessagePwdverifyPageCtrl',
                        templateUrl: 'templates/vip/vip_message_pwdverify.html',
                    }
                }
            })
            .state('app.vip_message', { //会员信息
                url: '/vip_message',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipMessagePageCtrl',
                        templateUrl: 'templates/vip/vip_message.html',
                    }
                }
            })
            .state('app.vip_red', { //红包
                url: '/vip_red/:curren/:redid',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipRedPageCtrl',
                        templateUrl: 'templates/vip/vip_red.html',
                    }
                }
            })
            .state('app.vip_red_withdraw', { //红包提现
                url: '/vip_red_withdraw',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipRedWithdrawPageCtrl',
                        templateUrl: 'templates/vip/vip_red_withdraw.html',
                    }

                }
            })
            .state('app.vip_red_withdrawEnd', { //红包提现完成
                url: '/vip_red_withdrawEnd/:mone',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipRedWithdrawEndPageCtrl',
                        templateUrl: 'templates/vip/vip_red_withdrawEnd.html',
                    }
                }
            })
            .state('app.vip_red_detail', { //红包提现明细
                url: '/vip_red_detail',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'vipRedDetailPageCtrl',
                        templateUrl: 'templates/vip/vip_red_detail.html',
                    }
                }
            })
            .state('app.vip', { //会员中心
                url: '/vip',
                cache: false,
                views: {
                    'menuContent': {
                        templateUrl: 'templates/vip/vip.html',
                    }
                }
            })
            .state('app.red', { //红包活动
                url: '/red/:id',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'RedCtrl',
                        templateUrl: 'templates/red/red.html',
                    }
                }
            })

            .state('app.redUserList', { //领取记录
                url: '/redUserList/:id',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'redUserListPageCtrl',
                        templateUrl: 'templates/red/redUserList.html',
                    }
                }
            })

            .state('app.redList', { //活动列表
                url: '/redList',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'redListPageCtrl',
                        templateUrl: 'templates/red/redList.html',
                    }
                }
            })

            .state('app.notice', { //通知中心
                url: '/notice',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'noticePageCtrl',
                        templateUrl: 'templates/notice/notice.html',
                    }
                }
            })

            .state('app.notice_data', { //通知详情
                url: '/notice_data/:id',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'noticeDataPageCtrl',
                        templateUrl: 'templates/notice/notice_data.html',
                    }
                }
            })

            .state('app.message', { //资讯中心
                url: '/message',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'messagePageCtrl',
                        templateUrl: 'templates/notice/message.html',
                    }
                }
            })

            .state('app.message_data', { //资讯详情
                url: '/message_data/:id',
                cache: false,
                views: {
                    'menuContent': {
                        controller: 'messageDataPageCtrl',
                        templateUrl: 'templates/notice/message_data.html',
                    }
                }
            });

        // if none of the above states are matched, use this as the fallback
        // $urlRouterProvider.otherwise('/app/YanZhiBao');
        // $urlRouterProvider.otherwise('/main'); //测试
        $urlRouterProvider.otherwise('/app/home');

    }]);


setTimeout(function() {
    // codePush.sync(); //下载更新
}, 5000);
